
document.querySelector('form').addEventListener('submit', function(e) {
    let isValid = true;

    // 验证用户名
    const username = document.getElementById('username').value.trim();
    if (username.length < 3 || username.length > 20) {
        document.getElementById('usernameError').textContent = '用户名长度应在3到20个字符之间';
        document.getElementById('usernameError').style.display = 'block';
        isValid = false;
    }

    // 验证密码
    const password = document.getElementById('password').value;
    if (password.length < 6) {
        document.getElementById('passwordError').textContent = '密码长度至少为6个字符';
        document.getElementById('passwordError').style.display = 'block';
        isValid = false;
    }

    // 验证确认密码
    const confirmPassword = document.getElementById('confirmPassword').value;
    if (password !== confirmPassword) {
        document.getElementById('confirmPasswordError').textContent = '两次输入的密码不一致';
        document.getElementById('confirmPasswordError').style.display = 'block';
        isValid = false;
    }

    // 验证邮箱
    const email = document.getElementById('email').value;
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
        document.getElementById('emailError').textContent = '请输入有效的邮箱地址';
        document.getElementById('emailError').style.display = 'block';
        isValid = false;
    }

    if (!isValid) {
        e.preventDefault();
    }
});

document.getElementById('avatar').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
            document.getElementById('avatarError').textContent = '请选择有效的图片文件';
            document.getElementById('avatarError').style.display = 'block';
            return;
        }

        // 验证文件大小
        if (file.size > 2 * 1024 * 1024) { // 2MB
            document.getElementById('avatarError').textContent = '文件大小不能超过2MB';
            document.getElementById('avatarError').style.display = 'block';
            return;
        }

        // 显示预览
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('preview').src = e.target.result;
            document.getElementById('imagePreview').style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
});


document.querySelector('form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch(this.action, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = '/success-page';
        } else {
            alert(data.message || '注册失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('请求失败，请稍后重试');
    });
});